/*
 * PropertyBlock.java
 *
 * Created on July 27, 2007, 11:33 AM
 *
 * Copyright (C) 2007 Akhmad Fathonih (akhmadf@gmail.com)
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 *
 * Changelog:
 * 2007/09/28
 *      - Add proper exception when writing to datablock
 */

package com.gamatechno.anybinding.core;

import com.gamatechno.anybinding.core.DataBlock;
import com.gamatechno.anybinding.marshaller.*;

/**
 *
 * @author geek
 */
public class PropertyBlock<T> implements IPropertyBlock<T> {
    private DataBlock datablock;
    private int MaxByteSize;

    /** Creates a new instance of PropertyBlock */
    public PropertyBlock(DataBlock block) {
        this.datablock = block;
        this.MaxByteSize = block.EndIndex - block.BeginIndex + 1;
    }
    
    public T value() throws PropertyInsufficientBytesLengthException {
        byte[] bytes = this.datablock.value();
        
        if (bytes.length > MaxByteSize)
            throw new PropertyInsufficientBytesLengthException("Data underflow on block '" + 
                    this.datablock.Alias + "'. About to write " + bytes.length + " of max " + MaxByteSize + " bytes", this.datablock);
        
        return ( (Marshallable<T>) this.datablock.getMarshallObj()).unserialized(bytes);
    }    
    
    public T value(boolean useCache) {
        return ( (Marshallable<T>) this.datablock.getMarshallObj()).unserialized(this.datablock.value(useCache));
    }
    
    public void setValue(T data) throws PropertyWriteException {
        Marshallable<T> marshall = (Marshallable<T>) this.datablock.getMarshallObj();
        byte[] bytes = marshall.serialized(data);
        if (bytes.length > MaxByteSize)
            throw new PropertyWriteException("Data overflow on block '" + 
                    this.datablock.Alias + "'. About to write " + bytes.length + " of max " + MaxByteSize + " bytes", this.datablock);
        
        this.datablock.setCachedValue(bytes);
    }
}
